const vscode = require('vscode');
const fs = require('fs');
const path = require('path');

/**
 * 激活插件
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {
    console.log('Chinese I18n Replacer 插件已激活');

    // 注册替换选中文本的命令
    let replaceCommand = vscode.commands.registerCommand('chinese-replacer.replaceSelected', async () => {
        await replaceSelectedText();
    });

    // 注册选择语言文件的命令
    let selectFileCommand = vscode.commands.registerCommand('chinesereplacer.selectLangFile', async () => {
        await selectLanguageFile();
    });

    context.subscriptions.push(replaceCommand, selectFileCommand);
}

/**
 * 替换选中的中文文本
 */
async function replaceSelectedText() {
    const editor = vscode.window.activeTextEditor;
    if (!editor) {
        vscode.window.showErrorMessage('请先打开一个文件');
        return;
    }

    const selection = editor.selection;
    const selectedText = editor.document.getText(selection);

    if (!selectedText) {
        vscode.window.showErrorMessage('请先选中要替换的中文文本');
        return;
    }

    // 检查选中的文本是否包含中文
    if (!containsChinese(selectedText)) {
        vscode.window.showErrorMessage('选中的文本不包含中文字符');
        return;
    }

    try {
        // 获取多语言文件内容
        const langData = await loadLanguageFile();
        if (!langData) {
            return;
        }

        // 查找匹配的key
        const matchedKey = findKeyByValue(langData, selectedText.trim());
        
        if (matchedKey) {
            // 找到匹配的key，进行替换
            await replaceWithKey(editor, selection, matchedKey);
        } else {
            // 没有找到匹配的key，提示用户
            const shouldAdd = await vscode.window.showQuickPick(
                ['是', '否'],
                {
                    placeHolder: `未找到匹配的key，是否将 "${selectedText}" 添加到多语言文件？`
                }
            );

            if (shouldAdd === '是') {
                await addNewTranslation(selectedText.trim(), editor, selection);
            }
        }
    } catch (error) {
        vscode.window.showErrorMessage(`操作失败: ${error.message}`);
    }
}

/**
 * 选择语言文件
 */
async function selectLanguageFile() {
    const options = {
        canSelectMany: false,
        openLabel: '选择多语言文件',
        filters: {
            'JavaScript files': ['js'],
            'JSON files': ['json'],
            'All files': ['*']
        }
    };

    const fileUri = await vscode.window.showOpenDialog(options);
    if (fileUri && fileUri[0]) {
        const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
        if (workspaceRoot) {
            const relativePath = path.relative(workspaceRoot, fileUri[0].fsPath);
            await vscode.workspace.getConfiguration('chineseReplacer').update(
                'langFilePath',
                relativePath,
                vscode.ConfigurationTarget.Workspace
            );
            vscode.window.showInformationMessage(`多语言文件路径已设置为: ${relativePath}`);
        }
    }
}

/**
 * 加载多语言文件
 */
async function loadLanguageFile() {
    const config = vscode.workspace.getConfiguration('chineseReplacer');
    let langFilePath = config.get('langFilePath');

    if (!langFilePath) {
        // 如果没有配置路径，尝试自动搜索
        if (config.get('autoSearch')) {
            langFilePath = await autoSearchLanguageFile();
        }
        
        if (!langFilePath) {
            const action = await vscode.window.showErrorMessage(
                '未找到多语言文件，请配置文件路径',
                '选择文件',
                '手动配置'
            );
            
            if (action === '选择文件') {
                await selectLanguageFile();
                return null;
            } else if (action === '手动配置') {
                vscode.commands.executeCommand('workbench.action.openSettings', 'chineseReplacer.langFilePath');
                return null;
            }
            return null;
        }
    }

    const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
    if (!workspaceRoot) {
        vscode.window.showErrorMessage('请在工作区中打开项目');
        return null;
    }

    const fullPath = path.isAbsolute(langFilePath) ? langFilePath : path.join(workspaceRoot, langFilePath);

    if (!fs.existsSync(fullPath)) {
        vscode.window.showErrorMessage(`多语言文件不存在: ${fullPath}`);
        return null;
    }

    try {
        // 清除require缓存，确保获取最新内容
        delete require.cache[require.resolve(fullPath)];
        
        let content;
        if (fullPath.endsWith('.json')) {
            const rawContent = fs.readFileSync(fullPath, 'utf8');
            content = JSON.parse(rawContent);
        } else {
            // 处理.js文件
            content = require(fullPath);
            // 如果是module.exports格式
            if (content.default) {
                content = content.default;
            }
        }

        return content;
    } catch (error) {
        vscode.window.showErrorMessage(`读取多语言文件失败: ${error.message}`);
        return null;
    }
}

/**
 * 自动搜索多语言文件
 */
async function autoSearchLanguageFile() {
    const config = vscode.workspace.getConfiguration('chineseReplacer');
    const searchPaths = config.get('searchPaths') || [];
    const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;

    if (!workspaceRoot) {
        return null;
    }

    for (const searchPath of searchPaths) {
        const fullPath = path.join(workspaceRoot, searchPath);
        if (fs.existsSync(fullPath)) {
            // 自动设置找到的路径
            await vscode.workspace.getConfiguration('chineseReplacer').update(
                'langFilePath',
                searchPath,
                vscode.ConfigurationTarget.Workspace
            );
            vscode.window.showInformationMessage(`自动找到多语言文件: ${searchPath}`);
            return searchPath;
        }
    }

    return null;
}

/**
 * 检查文本是否包含中文
 */
function containsChinese(text) {
    return /[\u4e00-\u9fa5]/.test(text);
}

/**
 * 在多语言对象中查找匹配的key
 */
function findKeyByValue(obj, value, prefix = '') {
    for (const key in obj) {
        const currentKey = prefix ? `${prefix}.${key}` : key;
        
        if (typeof obj[key] === 'string') {
            if (obj[key] === value) {
                return currentKey;
            }
        } else if (typeof obj[key] === 'object' && obj[key] !== null) {
            const result = findKeyByValue(obj[key], value, currentKey);
            if (result) {
                return result;
            }
        }
    }
    return null;
}

/**
 * 用key替换选中的文本
 */
async function replaceWithKey(editor, selection, key) {
    const config = vscode.workspace.getConfiguration('chineseReplacer');
    const keyPrefix = config.get('keyPrefix') || 't';
    
    const replacementText = `${keyPrefix}('${key}')`;
    
    await editor.edit(editBuilder => {
        editBuilder.replace(selection, replacementText);
    });

    vscode.window.showInformationMessage(`已替换为: ${replacementText}`);
}

/**
 * 添加新的翻译条目
 */
async function addNewTranslation(chineseText, editor, selection) {
    // 提示用户输入key
    const key = await vscode.window.showInputBox({
        prompt: '请输入该中文对应的key值',
        placeHolder: '例如: common.confirm',
        value: generateKeyFromText(chineseText)
    });

    if (!key) {
        return;
    }

    try {
        // 获取语言文件路径
        const config = vscode.workspace.getConfiguration('chineseReplacer');
        const langFilePath = config.get('langFilePath');
        const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
        const fullPath = path.join(workspaceRoot, langFilePath);

        // 读取现有内容
        let content = {};
        if (fs.existsSync(fullPath)) {
            if (fullPath.endsWith('.json')) {
                const rawContent = fs.readFileSync(fullPath, 'utf8');
                content = JSON.parse(rawContent);
            } else {
                // 对于.js文件，需要手动解析
                const rawContent = fs.readFileSync(fullPath, 'utf8');
                // 这里简化处理，假设是标准的export格式
                try {
                    delete require.cache[require.resolve(fullPath)];
                    content = require(fullPath);
                    if (content.default) {
                        content = content.default;
                    }
                } catch (e) {
                    content = {};
                }
            }
        }

        // 添加新的翻译
        setNestedValue(content, key, chineseText);

        // 写回文件
        if (fullPath.endsWith('.json')) {
            fs.writeFileSync(fullPath, JSON.stringify(content, null, 2), 'utf8');
        } else {
            // 对于.js文件，生成新的内容
            const jsContent = `module.exports = ${JSON.stringify(content, null, 2)};`;
            fs.writeFileSync(fullPath, jsContent, 'utf8');
        }

        // 替换编辑器中的文本
        await replaceWithKey(editor, selection, key);
        
        vscode.window.showInformationMessage(`已添加翻译 "${key}": "${chineseText}" 并完成替换`);
    } catch (error) {
        vscode.window.showErrorMessage(`添加翻译失败: ${error.message}`);
    }
}

/**
 * 根据中文文本生成建议的key
 */
function generateKeyFromText(text) {
    // 移除特殊字符，转换为拼音或英文（这里简化处理）
    return text.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, '').toLowerCase();
}

/**
 * 设置嵌套对象的值
 */
function setNestedValue(obj, path, value) {
    const keys = path.split('.');
    let current = obj;
    
    for (let i = 0; i < keys.length - 1; i++) {
        const key = keys[i];
        if (!(key in current) || typeof current[key] !== 'object') {
            current[key] = {};
        }
        current = current[key];
    }
    
    current[keys[keys.length - 1]] = value;
}

/**
 * 停用插件
 */
function deactivate() {}

module.exports = {
    activate,
    deactivate
};